using System;
using System.Collections.Generic;
using System.Text;

using System.Web;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.ApplicationPages;

using WMOSSExperts.Fields;
using WMOSSExperts.Diagnostics;

namespace WMOSSExperts.Pages
{
    public class RoutingRequest : System.Web.UI.Page
    {
        private const String _kRouteRelatedItems = "ViewRelatedItems";
        private const String _kRouteParentItem = "ViewParentItem";



        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            String route = Request.QueryString["Route"];
            String redirectUrl = String.Empty;
            switch (route)
            {
                case _kRouteRelatedItems:
                    redirectUrl = this.GetViewUrlToShowRelatedItems();
                    break;
                case _kRouteParentItem:
                    redirectUrl = this.GetViewUrlToShowParentItem();
                    break;
            }

            if (!String.IsNullOrEmpty(redirectUrl))
            {
                HttpContext.Current.Response.Redirect(redirectUrl);
            }
            else
                throw new SPException("The requested url has not been found...\n");
        }

        /// <summary>
        /// Get the url to view relatedItems
        /// </summary>
        private String GetViewUrlToShowRelatedItems()
        {
            String sourceListUrl = Request.QueryString["Source"];
            String fieldID = Request.QueryString["FieldID"];
            String parentId = Request.QueryString["Value"];
            if (String.IsNullOrEmpty(sourceListUrl) | String.IsNullOrEmpty(fieldID) | String.IsNullOrEmpty(parentId)) return String.Empty;

            try
            {

                SPList sourceList = SPContext.Current.Web.GetList(sourceListUrl);
                if (sourceList == null) return String.Empty;
                
                AdvancedLookupField reverseLookupField = (sourceList.Fields[new Guid(fieldID)] as AdvancedLookupField);
                if (reverseLookupField == null) return String.Empty;

                using (SPWeb web = SPContext.Current.Site.OpenWeb(reverseLookupField.LookupWebId))
                {
                    SPList targetList = web.Lists[new Guid(reverseLookupField.LookupList)];
                    AdvancedLookupField lookupField = (targetList.Fields.GetFieldByInternalName(reverseLookupField.LookupField) as AdvancedLookupField);

                    SPView filteredView = targetList.Views[lookupField.FilteredViewGuid];

                    String url = SPUrlUtility.CombineUrl(web.Url, filteredView.Url);
                    url += "?Value=" + parentId;

                    return url;

                }
            }
            catch (Exception ex)
            {
                TraceProvider.WriteTrace(TraceProvider.TraceSeverity.Exception, LogCategory.WMOSSExpertsCore, String.Format("GetViewUrlToShowRelatedItems fails for source sourceList {0} and related Field id {1} cause to the following error {2}",sourceListUrl,fieldID,ex));
                return String.Empty;
            }
        }

        /// <summary>
        /// Get the url to display parent item detail
        /// </summary>
        private String GetViewUrlToShowParentItem()
        {
            String sourceListUrl = Request.QueryString["Source"];
            String fieldID = Request.QueryString["FieldID"];
            String parentId = Request.QueryString["Value"];
            if (String.IsNullOrEmpty(sourceListUrl) | String.IsNullOrEmpty(fieldID) | String.IsNullOrEmpty(parentId)) return String.Empty;

            try
            {

                SPList sourceList = SPContext.Current.Web.GetList(sourceListUrl);
                if (sourceList == null) return String.Empty;

                AdvancedLookupField reverseLookupField = (sourceList.Fields[new Guid(fieldID)] as AdvancedLookupField);
                if (reverseLookupField == null) return String.Empty;

                using (SPWeb web = SPContext.Current.Site.OpenWeb(reverseLookupField.LookupWebId))
                {
                    SPList targetList = web.Lists[new Guid(reverseLookupField.LookupList)];
                    String dispFormUrl = targetList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;

                    dispFormUrl = SPUrlUtility.CombineUrl(web.Url, dispFormUrl);
                    dispFormUrl += "?ID=" + parentId;
                    if (Request.UrlReferrer != null && !Request.UrlReferrer.OriginalString.ToLower().Contains("source"))
                        dispFormUrl += "&Source=" + SPEncode.UrlEncode(Request.UrlReferrer.OriginalString);

                    return dispFormUrl;

                }
            }
            catch (Exception ex)
            {
                TraceProvider.WriteTrace(TraceProvider.TraceSeverity.Exception, LogCategory.WMOSSExpertsCore, String.Format("GetViewUrlToShowRelatedItems fails for source sourceList {0} and related Field id {1} cause to the following error {2}", sourceListUrl, fieldID, ex));
                return String.Empty;
            }
        }
    }
}
